package com.hunan.chinamobile.push;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

/**
 * Created by YangTang
 **/
public class MessagePush {

    static final Logger logger = LoggerFactory.getLogger(MessagePush.class);

    static final String MASTER_SECRET = "29bf7707148e63d523478748";

    static final String APP_KEY = "c837052f3f45480a1bf26b70";

    static JPushClient jpushClient = null;

    static {
        jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());
    }

    public static void main(String[] args){

        // For push, all you need do is to build PushPayload object.
        //PushPayload payload = buildPushObject_all_all_alert("欧文35分创绿衫军生涯新高");

        //PushPayload payload = sendAlert("胜顶电管家ios平台v1.2版本已上线，如果出现升级时跳转的应用地址不正确（“跳转到电气安全卫士”）请手动去app store中更新，给您造成的困扰敬请谅解。");
//        pushErrorData("设备位置：酒仙桥东路南口，设备一，故障事件,电压信号故障", Arrays.asList("a"),"stationError","2f5b1954-6028-4255-9446-8a55764de54e");
        //677566bd50224cbc9bc599b126c15d0d
//        try {
//            //PushResult result = jpushClient.sendPush(payload);
////            System.out.println(result);
//        } catch (APIConnectionException e) {
//            // Connection error, should retry later
//        } catch (APIRequestException e) {
//            // Should review the error, and fix the request
//        }

    }

    public static void pushAlert(String message){
        PushPayload payload = sendAlert(message);
        try {
            PushResult result = jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            // Connection error, should retry later
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
        }
    }


    /**
     * •快捷地构建推送对象：所有平台，所有设备，内容为 ALERT 的通知。
     * @return
     */
    public static PushPayload buildPushObject_all_all_alert(String alert) {
        return PushPayload.alertAll(alert);
    }

    public static PushPayload sendAlert(String alert) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setBadge(1)
                                .setSound("happy")
                                .addExtra("type", "message")
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .setBuilderId(3)
                                .addExtra("type", "message")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    public static void pushErrorData(String alert, List<String> userIds,String param,String bsId){
        PushPayload pushPayload = sendAlert2(alert, userIds, param, bsId);
        PushResult result = null;
        try {
            result = jpushClient.sendPush(pushPayload);
            System.out.println(JSON.toJSONString(result));
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    public static PushPayload sendAlert2(String alert, List<String> userIds,String flag,String bsId) {

        logger.info("PUSH ===> alert:"+alert+",userIds:"+ JSONArray.toJSONString(userIds)+",flag:"+flag+",bsId:"+bsId);

        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.alias(userIds))
                        .build())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setBadge(1)
                                .setSound("happy")
                                .addExtra("type", flag).addExtra("bsId",bsId)
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(alert)
                                .setBuilderId(3)
                                .addExtra("type", flag).addExtra("bsId",bsId)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    /**
     * •构建推送对象：所有平台，推送目标是别名为 "alias1"，通知内容为 ALERT。
     * @return
     */
    public static PushPayload buildPushObject_all_alias_alert(String alert) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias("alias1"))
                .setNotification(Notification.alert(alert))
                .build();
    }

    /**
     * •构建推送对象：平台是 Android，目标是 tag 为 "tag1" 的设备，内容是 Android 通知 ALERT，并且标题为 TITLE。
     * @return
     */
    public static PushPayload buildPushObject_android_tag_alertWithTitle(String alert,String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.android(alert, title, null))
                .build();
    }


    /**
     * •构建推送对象：平台是 iOS，推送目标是 "tag1", "tag_all" 的交集，
     * 推送内容同时包括通知与消息 - 通知信息是 ALERT，角标数字为 5，
     * 通知声音为 "happy"，并且附加字段 from = "JPush"；
     * 消息内容是 MSG_CONTENT。通知是 APNs 推送通道的，消息是 JPush 应用内消息通道的。
     * APNs 的推送环境是“生产”（如果不显式设置的话，Library 会默认指定为开发）
     * @return
     */
    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage(String alert,String message) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alert)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                .setMessage(Message.content(message))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    /**
     * •构建推送对象：平台是 Andorid 与 iOS，推送目标是 （"tag1" 与 "tag2" 的并集）交（"alias1" 与 "alias2" 的并集），
     * 推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush。
     * @return
     */
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String message) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(message)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static PushResult pushMessage(String userId){
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.alias(userId)).build())
                .setMessage(Message.newBuilder()
                                        .setTitle("Exit")
                                        .setContentType("T")
                                        .setMsgContent("Kicking out current users !")
                            .addExtra("from","JPush").build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build()).build();
        PushResult result = null;
        try {
            result = jpushClient.sendPush(pushPayload);
            System.out.println(JSON.toJSONString(result));
        } catch (APIConnectionException e) {
            // Connection error, should retry later
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
        }
        return result;
    }



}
